#!/usr/bin/php -q
<?	/*
	// File:	ssl_in.php
	// Purpose:	sits between stunnel and webcp-httpd to provide correct REMOTE_ADDR
	// Creation:	2003-03-06
	// Author:	Jonathan Haskins <jhaskins@killobyte.com>
			Felix <felix@wd1.net>
	*/
include_once('../web/functions.inc.phps');
load_globals();
// no output or magic quotes
ob_start();
set_magic_quotes_runtime(0);
// MAX LENGTH constant
define('MAX_LENGTH', 4096);
// include config
chdir(dirname(__FILE__));
include ('../web/config.inc.php');
// open input stream
$stunnel_in = fopen("php://stdin", 'r');
set_file_buffer($stunnel_in, 0);
// receive data from input client
$send = '';
$i = 0;
$length = 0;
$headerlength = 0;
while (!feof($stunnel_in)) {
	++ $i;
	$send .= fread($stunnel_in, 2);
	if (!$headerlength) {
		// detect end of headers
		if ($headerlength = strpos($send, "\r\n\r")) {
			$headerlength += 4;

			if (strlen($send) != $headerlength) {
				$send .= fgetc($stunnel_in);
			}
			// detect content-length or break input reading
			if ($length = stristr($send, 'Content-Length:')) {
				$length = substr($length, 0, strpos($length, "\r\n"));
				$length = explode(' ', $length);
				$length = $length[1];

				// read remaining chunk of data
				$send .= fread($stunnel_in, $length - 2);
			}
			else
				break;
		}
	}
	// check if all content (POST) is received
	elseif (($length + $headerlength) <= strlen($send))
		break;
}
// die if nothing came in (less than 2 lines)
if ($i < 2)
	return("Invalid request");
// close input stream
fclose($stunnel_in);
// add remote IP on top of all transmission
$send = trim($_SERVER['REMOTE_HOST'])."\r\n".trim($send)."\r\n\r\n";
// open connection stream to webcp-httpd
if (!$webcp = fsockopen("localhost", $cfg['ssl_port'], $errno, $errstr))
	die("Connection to webcp-httpd failed");
else // turn off blocking
	socket_set_blocking($webcp, false);
// send request data to webcp-httpd
fwrite($webcp, $send, strlen($send));
// open output stream
$stunnel_out = fopen("php://stdout", 'w');
set_file_buffer($stunnel_out, 0);
// receive data from webcp-httpd & send it back to the client
while (!feof($webcp))
	fwrite($stunnel_out, ($recieve = fread($webcp, MAX_LENGTH)), strlen($recieve));
// close webcp-httpd stream
fclose($webcp);
// close output stream
fclose($stunnel_out);
// clean input
ob_end_clean();
exit;
?>
